package com.luoran.car.controller;


import cn.hutool.jwt.JWT;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.luoran.car.config.UploadMinioUtils;
import com.luoran.car.domain.Coupon;
import com.luoran.car.domain.Type;
import com.luoran.car.service.CouponService;

import com.luoran.car.service.TypeService;
import com.luoran.car.util.Result;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("coupon")
public class CouponController {
    @Autowired
    private CouponService couponService;
     @Autowired
    private TypeService typeService;
     @Autowired
     private HttpServletRequest request;
     @RequestMapping("getById")
     public Result getById(Integer id){
      Coupon coupo= couponService.getById(id);
      return Result.success(coupo);
     }
    @RequestMapping("/buy")
    public Result getCoupen(Integer couponId){
        String token = request.getHeader("token");
        if(token.equals("")){
            return Result.fail("请先登录");
        }
        System.err.println("sss"+token);
        Integer customerId = (Integer) JWT.of(token).getPayload("id");
        System.err.println("ssss"+couponId);
        boolean b= couponService.getCoupen(couponId,customerId);
       return b?Result.success():Result.fail("优惠券数量已经抢完");
     }
    @RequestMapping("typeList")
    public Result typeList(){
       List<Type>list= typeService.list();
       return Result.success(list);
    }
    @RequestMapping("upload")
    public String upload(MultipartFile file){
        String s = UploadMinioUtils.uploadPic(file);
        return s;
    }
    @RequestMapping("save")
    public Result save(@RequestBody Coupon coupon){
       boolean flag= couponService.add(coupon);
      return Result.success(flag);
    }
    @RequestMapping("list")
    public Result list(@RequestBody Coupon coupon, Integer pageNum, Integer pageSize){
        String[] createTimes = coupon.getCreateTimes();
        if(createTimes!=null && createTimes.length>0){
            coupon.setStTime(createTimes[0]);
            coupon.setEnTime(createTimes[1]);
        }
        PageHelper.startPage(pageNum,pageSize);
       List<Coupon>list= couponService.lists(coupon);
        PageInfo<Coupon> info = new PageInfo<>(list);
        return Result.success(info);
    }
    @RequestMapping("newList")
    public Result newList(){
       List<Coupon>list= couponService.newList();
        return Result.success(list);
    }
}
